Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

execute task in main thread synchronously #195

Merged
merged 2 commits into from
Feb 16, 2019
Merged

Conversation

remirobert
Copy link

Related to #194

@uias-bot
Copy link
Member

1 Warning
⚠️ Looks like you changed some source files, should there have been some tests added?

Generated by 🚫 Danger

@RamblinWreck77
Copy link
Contributor

RamblinWreck77 commented Feb 14, 2019

@remirobert @msaps

I really liked this extension you made and decided to implement it in our project as it is just so much cleaner then all the Thread.isMainThread checks. In doing so I ran into a few issues and made some small tweaks I think are worth considering:

-The original implementation requires you to capture self (filling your code with either strong self captures or weak self and optional chaining) which is unnecessary since this is a synchronous block.

-Sometimes you want to return things from these blocks so we could use a return method.

extension DispatchQueue {

    static func mainThreadDo(callback: () -> Void) {
        if Thread.isMainThread {
            callback()
        } else {
            DispatchQueue.main.sync {
                callback()
            }
        }
    }

    static func mainThreadReturn<T>(callback: () -> T) -> T {
        if Thread.isMainThread {
            return callback()
        } else {
            var result: T!
            DispatchQueue.main.sync {
                result = callback()
            }
            return result
        }
    }
}

This way requires no self capture at all, and in practice looks like:

Logging to Crashlytics:

DispatchQueue.mainThreadDo {
    CLSLogv("%@", getVaList([log]))
}

Generating a mail controller:

let mfController = DispatchQueue.mainThreadReturn {
    return _generateMailController(subject: subject)
}

@remirobert
Copy link
Author

@RamblinWreck77 it looks very good thanks for sharing !

@msaps
Copy link
Member

msaps commented Feb 16, 2019

@remirobert is this good to go now?

@remirobert
Copy link
Author

@msaps all good

@msaps msaps merged commit e4cfab7 into uias:master Feb 16, 2019
@msaps
Copy link
Member

msaps commented Feb 17, 2019

Released in 3.0.4 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants